package auth

import (
	"context"
	"errors"

	// "time"

	"usercenter/internal/svc"
	"usercenter/internal/types"
	"usercenter/internal/utils"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserTokenLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserTokenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserTokenLogic {
	return &UserTokenLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserTokenLogic) UserToken(req *types.UserTokenRequest) (resp *types.UserTokenResponse, err error) {
	// 1. 验证refreshToken
	claims, err := utils.ParseToken(req.RefreshToken, l.svcCtx.Config.JWT.RefreshSecret)
	if err != nil {
		return nil, errors.New("无效的refresh token")
	}

	// 2. 检查Redis中的refreshToken
	tokenStore := utils.NewTokenStore(l.svcCtx.Redis, int(l.svcCtx.Config.JWT.RefreshExpire))
	storedToken, err := tokenStore.GetRefreshToken(l.ctx, claims.UserId)
	if err != nil || storedToken != req.RefreshToken {
		return nil, errors.New("refresh token已失效")
	}

	// 3. 生成新token
	authConf := utils.AuthConfig{
		AccessSecret:  l.svcCtx.Config.JWT.AccessSecret,
		AccessExpire:  l.svcCtx.Config.JWT.AccessExpire,
		RefreshSecret: l.svcCtx.Config.JWT.RefreshSecret,
		RefreshExpire: l.svcCtx.Config.JWT.RefreshExpire,
	}

	newAccessToken, newRefreshToken, err := utils.GenerateTokenPair(claims.UserId, authConf)
	if err != nil {
		return nil, errors.New("生成token失败")
	}

	// 4. 更新Redis中的refreshToken
	if err := tokenStore.StoreRefreshToken(l.ctx, claims.UserId, newRefreshToken); err != nil {
		logx.Errorf("更新refreshToken失败: %v", err)
		return nil, errors.New("系统错误")
	}

	return &types.UserTokenResponse{
		Code:    200,
		Message: "success",
		Data: types.TokenData{
			AccessToken:  newAccessToken,
			RefreshToken: newRefreshToken,
		},
	}, nil
}
